<?php


namespace App\Http\Controllers\Backend;


use App\Http\Requests\Company\VideoMakerRequest;
use App\Services\Business\Interfaces\QuestionServiceInterface;
use App\Services\Business\Models\UserVideoQuestion;
use App\Services\Business\Services\QuestionService;
use App\Services\Company\Models\Company;
use App\Services\Business\Interfaces\PromotionServiceInterface;

use App\Services\Business\Models\Course;
use App\Services\Business\Models\VideoMaker;
use App\Services\Business\Services\PromotionService;
use App\Services\Company\Models\CompanyCategory;
use Carbon\Carbon;
use App\Bus\VideoBus;
use App\Businesses\BusinessState;
use App\Constant\ApiV2Constant;
use App\Http\Requests\Company\VideoRequest;

use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Interfaces\CourseServiceInterface;
use App\Services\Business\Interfaces\VideoServiceInterface;

use App\Services\Business\Models\Video;
use App\Services\Business\Services\BusinessService;
use App\Services\Business\Services\VideoService;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Business\Services\NoteService;
use App\Services\Business\Interfaces\NoteServiceInterface;
use App\Services\Member\Services\UserService;
use App\Services\Order\Interfaces\OrderServiceInterface;
use App\Services\Order\Services\OrderService;
use App\Services\Business\Interfaces\IssueServiceInterface;
use App\Services\Business\Services\IssueService;
use App\Services\Business\Interfaces\RecommendServiceInterface;
use App\Services\Business\Services\RecommendService;
use App\Services\Business\Interfaces\CategoryServiceInterface;
use App\Services\Business\Services\CategoryService;
use App\Services\Company\Services\CompanyService;
use App\Services\Company\Interfaces\CompanyServiceInterface;


use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;


class VideoController extends BaseController
{


    /**
     * @var CompanyService
     */
    protected $CompanyService;

    /**
     * @var IssueService
     */
    protected $issueService;
    /**
     * @var PromotionService
     */
    protected $promotionService;

    /**
     * @var RecommendService
     */
    protected $recommendService;

    /**
     * @var VideoService
     */
    protected $videoService;
    /**
     * @var ConfigService
     */
    protected $configService;

    /**
     * @var UserService
     */
    protected $userService;
    /**
     * @var CourseService
     */
    protected $courseService;
    /**
     * @var NoteService
     */
    protected $noteService;
    /**
     * @var BusinessState
     */
    protected $businessState;
    /**
     * @var OrderService
     */
    protected $orderService;



    /**
     * @var CategoryService
     */
    protected $categoryService;

    /**
     * @var QuestionService
     */
    protected $questionService;


    public function __construct(
        CompanyServiceInterface         $CompanyService,
        VideoServiceInterface        $videoService,
        ConfigServiceInterface       $configService,
        UserServiceInterface         $userService,
        CourseServiceInterface       $courseService,
        BusinessState                $businessState,
        OrderServiceInterface        $orderService,
        NoteServiceInterface         $noteService,
        IssueServiceInterface        $issueService,
        RecommendServiceInterface    $recommendService,
        CategoryServiceInterface     $categoryService,
        QuestionServiceInterface     $questionService,

        PromotionServiceInterface    $promotionService

    )
    {
        $this->CompanyService = $CompanyService;
        $this->videoService = $videoService;
        $this->configService = $configService;
        $this->userService = $userService;
        $this->courseService = $courseService;
        $this->businessState = $businessState;
        $this->orderService = $orderService;
        $this->noteService = $noteService;
        $this->issueService = $issueService;
        $this->promotionService = $promotionService;
        $this->questionService = $questionService;

        $this->categoryService = $categoryService;
        $this->recommendService = $recommendService;
    }


    public
    function index(Request $request)
    {

        $companyId = $this->check() ? $this->loginCompanyId() : $request->input('company_id');
        $categoryId = $request->input('cid');
        $userIds = $request->input('user_ids');
        $keywords = $request->input('keywords');
        $sort = $request->input('sort', 'id');
        $courseId = $request->input('course_id', 0);
        $order = $request->input('order', 'desc');
        $excludeVideoIds = $request->input('exclude_ids', []);
        $currentVideoId = $request->input('current_video_id');


        $videos = Video::query()
            ->with(['user', 'tags'])
            ->where('is_show', 1)
            ->when($categoryId, function ($query) use ($categoryId) {
                $ids = [$categoryId];
                $childrenIds = CompanyCategory::query()
                    ->where('parent_id', $categoryId)
                    ->select(['id'])
                    ->get()
                    ->pluck('id')
                    ->toArray();
                $ids = array_merge($ids, $childrenIds);
                $query->whereIn('my_category_id', $ids);
            })
            ->when($courseId, function ($query) use ($courseId) {
                $query->where('course_id', $courseId);
            })
            ->when($userIds, function ($query) use ($userIds) {
                return $query->whereIn('user_id', $userIds);
            })
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($currentVideoId, function ($query) use ($currentVideoId, $excludeVideoIds) {
                //这里排除父id,当前编辑的id，还有已经
                $mappingVideoIds = $this->videoService->getVideoMappingIds($currentVideoId);
                $videoIds = array_merge($mappingVideoIds, $excludeVideoIds, [$currentVideoId]);
                $query->whereNotIn('id', $videoIds);
            })
            ->where('company_id', $companyId)
            ->orderBy($sort, $order)
            ->paginate($request->input('size', 10));
        return $this->successData(compact('videos'));
    }


    /**
     * 视频新增
     * @param VideoRequest $request
     * @param Video $video
     * @return JsonResponse
     */
    public
    function store(VideoRequest $request, Video $video)
    {

        $data = $request->filldata();
        $video->fill($data)->save($data);
        return $this->successData(compact('video'));
    }



    /**
     * 更新标题
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public
    function updateTitle(Request $request, $id)
    {
        $title = $request->input('title');
        $video = Video::query()->where('id', $id)->firstOrFail();
        $video->update(['title' => $title]);
        return $this->success(__('标题更新成功'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function updateThumb(Request $request, $id): JsonResponse
    {
        $thumb = $request->input('thumb');
        $article = Video::query()->where('id', $id)->firstOrFail();
        $article->update(['thumb' => $thumb]);
        return $this->success(__('封面更新成功'));
    }


    /**
     * 返回视频截图信息
     * @param Request $request
     * @return JsonResponse
     */
    public function getSnapshot(Request $request, $id): JsonResponse
    {


        $video = Video::find($id);
        $videoInfo = aliyun_video_info($video->aliyun_video_id);
        $snapshots = $videoInfo['Snapshots']['Snapshot'] ?? [];
        return $this->successData(compact('snapshots'));


    }


    public
    function show(Request $request, $id)
    {
        $video = Video::query()->where('id', $id)->firstOrFail();
        $result = empty($video->getAttribute('is_show')) ? 1 : 0;
        $video->update(['is_show' => $result]);
        return $this->successData(__('操作成功'));

    }


    /**
     * 删除视频
     * @param Video $video
     * @param ConfigServiceInterface $configService
     * @param VideoServiceInterface $videoService
     * @return JsonResponse
     */
    public
    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {


        $video = Video::find($id);
        DB::transaction(function () use ($video, $configService, $videoService) {


            //删除阿里云的附件
            $videoService->deleteVideo($video['aliyun_video_id'], $configService);

            $video->delete();


        });
        return $this->success(__('删除视频成功'));

    }




    public
    function playInfo(Request $request, $id)
    {


        $video = Video::query()->where('id', $id)->firstOrFail()->toArray();
        $urls = get_play_url($video, true);
        if (!$urls) {
            return $this->error(__('错误'));
        }

        return $this->successData(compact('urls'));
    }


    /**
     * @api {get} /api/v2/video/open/play 公共视频播放
     * @apiGroup 录播课
     * @apiVersion v2.0.0
     *
     * @apiParam {String} file_id 视频文件ID
     * @apiParam {String} service 视频文件存储服务
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     * @apiSuccess {String} data.url 播放URL
     * @apiSuccess {String} data.format 视频格式
     * @apiSuccess {Number} data.duration 时长,单位:秒
     * @apiSuccess {String} data.name 清晰度
     */


    /**
     * 批量转移课程
     * @param Request $request
     * @return JsonResponse
     */
    public
    function remove(Request $request)
    {
        $ids = $request->input('ids');
        $courseId = $request->input('course_id');
        $chapterId = $request->input('chapter_id');
        if (!$ids && !$courseId) {
            return $this->error(__('参数错误'));
        }
        $article = Video::query()->whereIn("id", $ids)->update(['course_id' => $courseId, 'chapter_id' => $chapterId]);
        return $this->success('操作成功');
    }


    /**
     * 更新试听视频
     * @param Request $request
     * @return JsonResponse
     */
    public
    function free(Request $request)
    {

        $ids = $request->input('ids', []);
        if (!$ids) {
            return $this->error(__('参数错误'));
        }
        if (is_string($ids)) {
            $ids = [$ids];
        }
        Video::query()->whereIn('id', $ids)->update(['is_free' => 1]);
        return $this->success(__('添加试听成功'));


    }

    public
    function unfree(Request $request)
    {

        $ids = $request->input('ids', []);
        if (!$ids) {
            return $this->error(__('参数错误'));
        }
        if (is_string($ids)) {
            $ids = [$ids];
        }
        Video::query()->whereIn('id', $ids)->update(['is_free' => 0]);
        return $this->success(__('取消试听成功'));


    }



    /**
     * @param VideoMakerRequest $request
     * @param $videoId
     * @return JsonResponse
     */
    public
    function storeMaker(VideoMakerRequest $request, $videoId): JsonResponse
    {
        $video = Video::find($videoId);
        $maker = new VideoMaker($request->filldata());
        $maker->video()->associate($video);
        $maker->save();
        return $this->successData(compact('maker'));
    }

    /**
     * @param VideoMakerRequest $request
     * @return JsonResponse
     */
    public
    function batchStoreMaker(VideoMakerRequest $request)
    {
        $makers = $request->input('items');
        DB::table('video_maker')->insert($makers);
        return $this->success(__('插入标记成功'));
    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    public
    function deleteMaker(Request $request)
    {
        $ids = $request->input('ids');
        if (!$ids) {
            return $this->error(__('参数错误'));
        }
        $ids = (!is_array($ids)) ? [$ids] : $ids;
        VideoMaker::destroy($ids);
        return $this->success(__('标记删除成功'));

    }

    public
    function storeMappings(Request $request, $id)
    {
        $ids = $request->input('ids');
        if (!$ids) {
            $this->error(__('参数错误'));
        }
        $video = Video::query()->where('id', $id)->firstOrFail();
        $video->mappings()->sync($ids);
        return $this->success(__('添加成功'));


    }

    /**
     * 视频下面的考题
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function questions(Request $request, int $id)
    {
        $size = $request->input('size', 10);
        $video = Video::find($id);
        $questions = $video->questions()->paginate($size);
        return $this->successData(compact('questions'));

    }


    /**
     * 新增绑定考题
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public
    function storeQuestion(Request $request, int $id)
    {
        $user = Auth::user();
        $video = Video::query()->where('id', $id)->first();
        $course = Course::query()->where('id', $video['course_id'])->first();
        $ids = (array)$request->input("ids", []);
        if (empty($id)) {
            return $this->error(__('参数错误'));
        }

        DB::transaction(function () use ($ids, $video, $course, $user) {
            foreach ($ids as $id) {
                // 检查是否已存在关联记录
                if (!$video->questions()->where('question_id', $id)->exists()) {
                    // 不存在时才添加新的关联记录并设置额外字段
                    $video->questions()->attach($ids, ['user_id' => $user['app_id'], 'company_id' => $user['login_company_id'], 'course_id' => $video['course_id']]);
                }
                // 如果存在且不需要更新额外字段，则直接跳过
            }

            //维护视频及课程下面的考题
            $course->increment('question_count', count($ids));
            $video->increment('question_count', count($ids));

        });


        return $this->success(__('绑定试题成功'));
    }

    /**
     * 删除视频下面的考题
     * @param Request $request
     * @param string $type
     * @param int $id
     * @return JsonResponse
     */
    public
    function deleteQuestion(Request $request, int $id)
    {
        $video = Video::query()->where('id', $id)->first();
        $course = Course::query()->where('id', $video['course_id'])->first();
        $ids = (array)$request->input("ids", []);
        if (empty($ids)) {
            return $this->error(__('参数错误'));
        }

        DB::transaction(function () use ($ids, $video, $course) {

            $video->questions()->detach($ids);
            //维护视频及课程下面的考题的数量
            $course->decrement('question_count', count($ids));
            $video->decrement('question_count', count($ids));

            //维护用户在考题下面的考题数量

            UserVideoQuestion::query()->whereIn('question_id', $ids)->delete();
        });


        return $this->success(__('取消绑定试题成功'));
    }

    /**
     * 获取最新一条绑定考题的视频及课程
     * @return JsonResponse
     */
    public
    function getBindVideo()
    {


        $user = Auth::user();
        ['video_id' => $video_id, 'course_id' => $course_id, 'course_title' => $course_title] = $this->questionService->getBindVideo($user['login_company_id']);

        return $this->successData(compact('video_id', 'course_id', 'course_title'));


    }


}
